# This Python file uses the following encoding: utf-8

# if __name__ == "__main__":
#     pass
#!/usr/bin/env python3

from launch import LaunchDescription
from launch.actions import ExecuteProcess, IncludeLaunchDescription, TimerAction
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch_ros.actions import Node
from ament_index_python.packages import get_package_share_directory  # 导入缺失的函数
import os

def generate_launch_description():
    # 1. 启动 micro_ros_agent
    micro_ros_agent = ExecuteProcess(
        cmd=["ros2", "run", "micro_ros_agent", "micro_ros_agent", "udp4", "--port", "8888", "-v6"],
        output="screen",
        name="micro_ros_agent"
    )

    # 2. 执行 Python 脚本，创建ydlidar虚拟串口
    ydlidar_x2_vir_serial = ExecuteProcess(
        cmd=["python3", "/home/tf/physical_robot/src/two_wheels_robot/scripts/ydlidar_x2_vir_serial.py"],
        output="screen",
        name="ydlidar_x2_vir_serial"
    )

    # 3. 增加 5 秒延时，再启动 ydlidar_launch.py，否则会因为没有虚拟串口导致ydlildar退出
    delay_ydlidar_launch = TimerAction(
        period=5.0,  # 延时 5 秒
        actions=[
            # 4. 启动 ydlidar_launch.py
            IncludeLaunchDescription(
                PythonLaunchDescriptionSource([
                    os.path.join(
                        # 替换为你的 ydlidar 包路径
                        get_package_share_directory("ydlidar"),
                        "launch",
                        "ydlidar_launch.py"
                    )
                ])
            )
        ]
    )

    rviz_node = Node(
        package='rviz2',
        executable='rviz2',
        name='rviz2',
        # arguments=['-d', rviz_config_dir],
        # parameters=[{'use_sim_time': use_sim_time}],
        output='screen')

    return LaunchDescription([
        micro_ros_agent,
        ydlidar_x2_vir_serial,
        delay_ydlidar_launch,
        rviz_node,
    ])
